//
//  WaitingReciveViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/1/29.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "WaitingReciveViewController.h"
#import "WaitingTableViewCell.h"
#import "WaitReciveIndentDetailViewController.h"
#import "ShopViewController.h"
#import "WaittingCommentDetailViewController.h"
static NSString *cellIdentify = @"WaitingTableViewCell";
@interface WaitingReciveViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray * indentsArray;

@end

@implementation WaitingReciveViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO =  1;
    self.indentsArray = [NSMutableArray array];

    [self initViewLayout];
    [self addRefreshing];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    //注册
    [self.tableView registerClass:[WaitingTableViewCell class]  forCellReuseIdentifier:cellIdentify];

    self.tableView.separatorStyle = NO;
}
- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}
- (IBAction)goHome:(id)sender {
    [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"ifLogin"];
    [self.navigationController  popViewControllerAnimated:YES];
}

- (void)shopInfoHandel:(UIButton * )sender{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ShopViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Shop"];
    NSInteger index = sender.tag/100-1;
    page.storeId = _indentsArray[index][@"mallStoreId"];
    [self.navigationController   pushViewController:page animated:YES];
    
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIndentsList];
        });
    }];
    
}
//加载更多数据
- (void)loadMoreData{
    if (self.indentsArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getIndentsList];
        });
    }
    
}


- (void)getIndentsList{
    
    NSDictionary * dic1 = [Common getLoginInfo];
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    [dic setObject:dic1[@"userId"] forKey:@"userId"];
    [dic setObject:@"appOrderList" forKey:@"method"];
    [dic setObject:@"4" forKey:@"mgorState"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_appOrderList withHttpType:@"POST" withTag:SX_SX_appOrderList];
    
}




#pragma mark == 订单操作按钮点击
- (void)indentControlHandel:(UIButton *)sender{
    //sender.tag%100 == 1  2  3
    NSInteger section = sender.tag/100-1;
    if (sender.tag%100 == 1) {//
        
    }else if(sender.tag%100 == 2){//申请售后
        
    }else if (sender.tag%100 == 3){//评价晒单

    }
    
    
}
#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _indentsArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray * array = _indentsArray[indexPath.section][@"goodsList"];
    return array.count*128*VerticalRatio();
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 38*VerticalRatio();
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 47*VerticalRatio();
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
    
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 38), NO)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel * label =  [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(35,0, 165, 38), NO)];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor colorWithWhite:0.196 alpha:1.000];
    label.font = [UIFont systemFontOfSize:15*VerticalTexeRatio()];
    label.text = [NSString stringWithFormat:@"%@",_indentsArray[section][@"mallStoreName"]];
    [view addSubview:label];
    
    UILabel * Label =  [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0,0, 305, 38), NO)];
    Label.textAlignment = NSTextAlignmentRight;
    Label.textColor = [UIColor colorWithRed:1.000 green:0.427 blue:0.337 alpha:1.000];
    Label.font = [UIFont systemFontOfSize:15*VerticalTexeRatio()];
    NSString * status = [NSString stringWithFormat:@"%@",_indentsArray[section][@"goodsList"][0][@"orderState"]];
    if ([status isEqualToString:@"1"]) {
        status = @"待支付";
    }else if([status isEqualToString:@"2"]){
        status = @"已支付";
    }else if([status isEqualToString:@"3"]){
        status = @"备货";
    }else if([status isEqualToString:@"4"]){
        status = @"等待收货";
    }else if([status isEqualToString:@"5"]){
        status = @"签收";
    }else if([status isEqualToString:@"6"]){
        status = @"取消";
    }else if([status isEqualToString:@"7"]){
        status = @"退款中";
    }else if([status isEqualToString:@"8"]){
        status = @"退款完成";
    }else if([status isEqualToString:@"9"]){
        status = @"退货中";
    }
    Label.text = status;
    [view addSubview:Label];
    
    CGSize strSize = [[NSString stringWithFormat:@"%@",_indentsArray[section][@"mallStoreName"]] sizeWithFont:[UIFont systemFontOfSize:15*VerticalTexeRatio()]];
    if (strSize.width>165*VerticalRatio()) {
        strSize.width = 165*VerticalRatio();
    }
    UIImageView * backImage = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(strSize.width+45,12, 8, 15), NO)];
    backImage.image = [UIImage imageNamed:@"shopping1"];
    [view addSubview:backImage];
    
    
    UIImageView * backimage = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(10,11, 19, 16), NO)];
    backimage.image = [UIImage imageNamed:@"personal17"];
    [view addSubview:backimage];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = flexibleFrame(CGRectMake(0, 0, 200, 38), NO);
    button.tag = 100*(section+1);
    [view addSubview:button];
    
    [button addTarget:self action:@selector(shopInfoHandel:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 37, 320, 1), YES)];
    line.backgroundColor = [UIColor colorWithWhite:0.855 alpha:1.000];
    [view addSubview:line];
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 47), YES)];
    view.backgroundColor= [UIColor whiteColor];
//    NSArray * array = @[@"删除订单",@"申请售后",@"晒单评价"];
    NSArray * array = @[@"退货/退款",@"确认收货"];
    for (int i = 0;i<array.count;i++) {
        UIButton * button  = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = flexibleFrame(CGRectMake(123+65+65*i, 10, 55, 21), NO);
        button.layer.borderWidth = 1;
        button.layer.cornerRadius = 3*VerticalRatio();
        button.layer.borderColor = [UIColor colorWithWhite:0.600 alpha:1.000].CGColor;
        button.backgroundColor = [UIColor whiteColor];
        [button setTitleColor:[UIColor colorWithWhite:0.600 alpha:1.000] forState:UIControlStateNormal];
        if (i==1) {
            button.layer.borderColor =  [UIColor colorWithRed:0.969 green:0.608 blue:0.090 alpha:1.000].CGColor;
            [button setTitleColor:[UIColor colorWithRed:0.969 green:0.608 blue:0.090 alpha:1.000] forState:UIControlStateNormal];
        }
        button.titleLabel.font = [UIFont systemFontOfSize:12*VerticalTexeRatio()];
        [button setTitle:array[i] forState:UIControlStateNormal];
        button.tag = 100*(section+1)+i+1;
        [button addTarget:self action:@selector(indentControlHandel:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
    }
    
    UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 42, 320, 5), YES)];
    line.backgroundColor = [UIColor colorWithWhite:0.855 alpha:1.000];
    [view addSubview:line];
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify forIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    NSArray * array = _indentsArray[indexPath.section][@"goodsList"];
    for (int i = 0; i<array.count; i++) {
        UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 127+128*i, 320, 1), YES)];
        line.backgroundColor = [UIColor colorWithWhite:0.855 alpha:1.000];
        [cell addSubview:line];
        
        //优惠劵
        UILabel * forSaleLabel = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(12, 128*i, 320, 35), YES)];
        forSaleLabel.textAlignment = NSTextAlignmentLeft;
        forSaleLabel.textColor = [UIColor colorWithWhite:0.518 alpha:1.000];
        forSaleLabel.font = [UIFont systemFontOfSize:14*VerticalTexeRatio()];
        NSMutableAttributedString *Str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"优惠劵: 已抵扣%@优惠劵",array[i][@"mgooPublishPrice"]]];
        [Str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.867 green:0.561 blue:0.000 alpha:1.000] range:NSMakeRange(0,4)];
        forSaleLabel.attributedText = Str;
        [cell addSubview:forSaleLabel];
        //图片
        UIImageView * goodsImage = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(12, 35+128*i, 78, 78), YES)];
        NSString * image = array[i][@"appAdertImagUriName"];
        if (image.length>0) {
            [goodsImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }else{
            goodsImage.image =[UIImage imageNamed:@"cloth1"];
        }
        [cell addSubview:goodsImage];
        
        //商品名
        UILabel * infoLabel = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(103, 40+128*i, 190, 20), NO)];
        infoLabel.numberOfLines = 0;
        infoLabel.textAlignment = NSTextAlignmentLeft;
        infoLabel.textColor = [UIColor colorWithWhite:0.196 alpha:1.000];
        infoLabel.font = [UIFont systemFontOfSize:13*VerticalTexeRatio()];
        infoLabel.text = [NSString stringWithFormat:@"%@",array[i][@"mgooName"]];
        [infoLabel sizeToFit];
        [cell addSubview:infoLabel];
        //商品规格
        UILabel * propertyLabel = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(103, 75+128*i, 190, 20), NO)];
        propertyLabel.numberOfLines = 0;
        propertyLabel.textAlignment = NSTextAlignmentLeft;
        propertyLabel.textColor = [UIColor colorWithWhite:0.631 alpha:1.000];
        propertyLabel.font = [UIFont systemFontOfSize:12*VerticalTexeRatio()];
        propertyLabel.text = [NSString stringWithFormat:@"%@",array[i][@"mgseSpecifyDetailJson"]];
        [propertyLabel sizeToFit];
        [cell addSubview:propertyLabel];
        
        
        //商品价格
        UILabel * priceLabel = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(102, 100+128*i, 150, 15), NO)];
        priceLabel.textAlignment = NSTextAlignmentLeft;
        priceLabel.textColor = [UIColor colorWithRed:0.859 green:0.161 blue:0.161 alpha:1.000];
        priceLabel.font = [UIFont systemFontOfSize:16*VerticalTexeRatio()];
        
        NSString * str = [NSString stringWithFormat:@"￥%@",[Common stringFromData:array[i][@"mgooPublishPrice"]]];
        NSString * oldPrice = [NSString stringWithFormat:@"￥%@",[Common stringFromData:array[i][@"mgooPublishPrice"]]];
        
        NSMutableAttributedString * price = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@     %@",str,oldPrice]];
        [price addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithWhite:0.612 alpha:1.000] range:NSMakeRange(price.length-oldPrice.length, oldPrice.length)];
        [price addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13*VerticalTexeRatio()] range:NSMakeRange(price.length-oldPrice.length, oldPrice.length)];
        [price addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(price.length-oldPrice.length, oldPrice.length)];
//        [price addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13*VerticalTexeRatio()] range:NSMakeRange(0, str.length)];
        
        priceLabel.attributedText = price ;
        
        [cell addSubview:priceLabel];
        
        //商品数量
        UILabel * numberLabel = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 102+128*i, 300, 15), NO)];
        numberLabel.textAlignment = NSTextAlignmentRight;
        numberLabel.textColor = [UIColor colorWithWhite:0.231 alpha:1.000];
        numberLabel.font = [UIFont systemFontOfSize:13*VerticalTexeRatio()];
        numberLabel.text = [NSString stringWithFormat:@"x%@",array[i][@"goodsCartNum"]];
        [cell addSubview:numberLabel];
        
        
    }
    
    
    
    return cell;
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"PersonCenterStoryboard" bundle:nil];
    WaittingCommentDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"WaittingCommentDetail"];
    page.indentId = _indentsArray[indexPath.section][@"maorId"];
    page.titleStr = @"待收货/使用";
    [self.navigationController   pushViewController:page animated:YES];
}



#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_tableView.header endRefreshing];
    if (tag==SX_SX_appOrderList){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.indentsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.indentsArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
            
            
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [self dismissWaitDialog];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
